import {
  deleteBisheProjectUsingPost,
  listBisheProjectByPageUsingPost,
} from '@/services/backend/bisheProjectController';
import { uploadFileUsingPost } from '@/services/backend/fileController';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProFormInstance,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import {
  Button,
  message,
  notification,
  Select,
  SelectProps,
  Space,
  Tag,
  Typography,
  Upload,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import CreateModal from './components/CreateModal';
import UpdateModal from './components/UpdateModal';

//常见的标签
const tagOptions: SelectProps['options'] = [
  { label: 'SpringBoot', value: 'SpringBoot' },
  { label: 'Vue', value: 'Vue' },
  { label: 'React', value: 'React' },
  { label: 'MySQL', value: 'MySQL' },
  { label: 'Python', value: 'Python' },
  { label: '前后端分离', value: '前后端分离' },
  { label: 'Uni-app', value: 'Uni-app' },
];

//复制文字到粘贴板
const setClipboard = (text: string = '') => {
  const type = 'text/plain';
  const blob = new Blob([text], { type });
  const copyData = [new ClipboardItem({ [type]: blob })];
  navigator.clipboard.write(copyData).then(
    () => {
      /* success */
      message.success(text);
    },
    () => {
      /* failure */
      return;
    },
  );
};

const TableList: React.FC = () => {
  const [params] = useSearchParams();
  const id = (params.get('id') ?? -1) as number;
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<API.BisheProject>();

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.BisheProject) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteBisheProjectUsingPost({
        id: row.id,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   * 初始化钩子
   */
  useEffect(() => {
    //当id存在时,进行条件查询
    if (id !== -1) {
      formRef.current?.setFieldsValue({
        id: id,
      });
      formRef.current?.submit();
    }
  }, []);

  const statusEnumMap = new Map([
    [0, { text: '关闭', status: 'Error' }],
    [1, { text: '开启', status: 'Success' }],
  ]);

  const columns: ProColumns<API.BisheProject>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '标题',
      dataIndex: 'title',
      valueType: 'text',
      ellipsis: true,
      tooltip: { title: '省略过长内容' },
    },
    {
      title: '子标题',
      dataIndex: 'subtitle',
      valueType: 'text',
      hideInSearch: true,
      ellipsis: true,
      tooltip: { title: '省略过长内容' },
    },
    {
      title: '功能演示URL',
      dataIndex: 'demoVideoUrl',
      valueType: 'text',
      render: (_, entity) => (
        <Typography.Link href={entity.demoVideoUrl} target={'_blank'}>
          点击跳转
        </Typography.Link>
      ),
      hideInSearch: true,
      copyable: true,
    },
    {
      title: '介绍文档',
      dataIndex: 'introduce',
      valueType: 'textarea',
      ellipsis: {
        showTitle: false,
      },
      tooltip: { title: '省略过长内容' },
      hideInSearch: true,
    },
    {
      title: '项目代码',
      dataIndex: 'codeDataUrl',
      valueType: 'text',
      hideInSearch: true,
      hideInForm: true,
      render: (_, entity) => (
        <>
          <Typography.Link href={entity.codeDataUrl} target={'_blank'}>
            点击下载
          </Typography.Link>
          <Typography.Paragraph>(定价{entity.codePrice})</Typography.Paragraph>
        </>
      ),
    },
    {
      title: '论文初稿',
      dataIndex: 'docDataUrl',
      valueType: 'text',
      hideInSearch: true,
      hideInForm: true,
      render: (_, entity) => (
        <>
          <Typography.Link href={entity.docDataUrl} target={'_blank'}>
            点击下载
          </Typography.Link>
          <Typography.Paragraph>(定价{entity.docPrice})</Typography.Paragraph>
        </>
      ),
    },
    {
      valueType: 'group',
      hideInTable: true,
      hideInSearch: true,
      //@ts-ignore
      columns: [
        {
          title: '代码价格',
          dataIndex: 'codePrice',
          valueType: 'digit',
          width: 'xs',
        },
        {
          title: '项目代码url',
          dataIndex: 'codeDataUrl',
          valueType: 'text',
          width: 'xl',
        },
      ],
    },
    {
      valueType: 'group',
      hideInTable: true,
      hideInSearch: true,
      //@ts-ignore
      columns: [
        {
          title: '论文价格',
          dataIndex: 'docPrice',
          valueType: 'digit',
          width: 'xs',
        },
        {
          title: '论文初稿url',
          dataIndex: 'docDataUrl',
          valueType: 'text',
          width: 'xl',
        },
      ],
    },

    {
      title: '毕设项目展示图片',
      dataIndex: 'cover',
      valueType: 'image',
      fieldProps: {
        width: 64,
      },
      hideInSearch: true,
    },
    {
      title: '访问数',
      dataIndex: 'clickNum',
      valueType: 'digit',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '标签',
      dataIndex: 'tagList',
      render: (_, record) =>
        record.tagList?.map((tag) => (
          <Tag color={'success'} key={tag}>
            {tag}
          </Tag>
        )),
      renderFormItem: () => {
        return (
          <Select
            mode="tags"
            style={{ width: '100%' }}
            placeholder="请选择标签"
            options={tagOptions}
          />
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: statusEnumMap,
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size={'middle'}>
          <Typography.Link
            key="config"
            onClick={() => {
              setUpdateModalVisible(true);
              setCurrentRow(record);
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link
            type="danger"
            onClick={() => {
              handleDelete(record);
            }}
          >
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.BisheProject>
        formRef={formRef}
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
          <Upload
            key="upload"
            multiple={false}
            maxCount={1}
            accept={'.zip'}
            showUploadList={false}
            customRequest={async (options) => {
              const { file, filename } = options;
              try {
                const res = await uploadFileUsingPost({ biz: 'user_avatar' }, {}, file as File);
                const { code, data } = res;
                if (code === 0) {
                  notification.success({
                    key: 'upload',
                    message: `${filename}上传成功`,
                    description: (
                      <>
                        <Typography.Text>下载地址:</Typography.Text>
                        <Typography.Link onClick={() => setClipboard(data)}>{data}</Typography.Link>
                      </>
                    ),
                    showProgress: true,
                    pauseOnHover: true,
                  });
                }
              } catch (e: any) {
                message.error(e.message);
              }
            }}
          >
            <Button type="primary" key="primary">
              <UploadOutlined /> 上传文件
            </Button>
          </Upload>,
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listBisheProjectByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.BisheProjectQueryRequest);
          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      {/*新增悬浮窗*/}
      <CreateModal
        modalVisible={createModalVisible}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      {/*更新悬浮窗*/}
      <UpdateModal
        oldData={currentRow}
        modalVisible={updateModalVisible}
        columns={columns}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default TableList;
